package com.example.administrator.myapplication;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ShareActionProvider;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity" ;
    EditText mEtData;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String jsonStr = "{\"temp\":\"20℃/30℃\",\"weather\":\"晴转多云\",\"name\":\"上海\",\"pm\":\"80\",\"wind\":\"1级\"}";
        String jsonArrayStr = "[\n" +
                "  {\"temp\":\"20℃/30℃\",\"weather\":\"晴转多云\",\"name\":\"上海\",\"pm\":\"80\",\"wind\":\"1级\"},\n" +
                "  {\"temp\":\"15℃/24℃\",\"weather\":\"晴\",\"name\":\"北京\",\"pm\":\"98\",\"wind\":\"3级\"},\n" +
                "  {\"temp\":\"26℃/32℃\",\"weather\":\"多云\",\"name\":\"广州\",\"pm\":\"30\",\"wind\":\"2级\"}\n" +
                "]\n";

        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            String temp = jsonObject.getString("temp");
            String weather = jsonObject.getString("weather");
            Log.e(TAG, "onCreate: "+temp);
            //解析JSON数组字符串

            JSONArray jsonArray = new JSONArray(jsonArrayStr);
            Log.e(TAG, "onCreate: "+jsonArrayStr.length() );


            for(int i = 0; i<jsonArray.length();i++){
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                temp = jsonObject1.getString("weather");
                weather = jsonObject1.getString("weather");
                Log.e(TAG, "onCreate: "+temp+"=="+weather );
            }





        } catch (JSONException e) {
            Log.e(TAG, "onCreate: " );
          //  e.printStackTrace();
        }


        mEtData = findViewById(R.id.et_data);
    }

    public void save(View view) {

        String data = mEtData.getText().toString();
        //保存到SP
        //1 得到SP对象的编辑器
       SharedPreferences sp = getSharedPreferences("data.sp",MODE_PRIVATE);
       SharedPreferences.Editor editor = sp.edit();// 从sp对象中获取编辑器editor
       //2 将数据写入SP
        editor.putString("name",data);
        // 3 保存提交commit
        editor.commit();
    }

    public void read(View view) {
        //1 获取SP对象
        SharedPreferences sp = getSharedPreferences("data.sp",MODE_PRIVATE);

        //2 读取内容
        String name = sp.getString("name","");

        //显示数据到tv_data
        TextView tvData = findViewById(R.id.tv_data);
        tvData.setText(name);
    }
}
